import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { progressService } from '@/services/progressService'

/**
 * 学习追踪组合式函数
 * 用于在各个章节页面中自动记录学习行为
 */
export function useStudyTracker() {
  const route = useRoute()
  const isTracking = ref(false)
  const startTime = ref<Date | null>(null)
  
  // 章节ID映射
  const chapterIdMap: { [key: string]: string } = {
    'chapter1': '1',
    'chapter2': '2', 
    'chapter3-examples': '3',
    'chapter4-examples': '4',
    'examples': '5'
  }
  
  /**
   * 获取当前章节ID
   */
  const getCurrentChapterId = (): string => {
    const routeName = route.name as string
    return chapterIdMap[routeName] || '1'
  }
  
  /**
   * 记录视频观看
   * @param videoTitle 视频标题
   * @param lessonId 课时ID（可选）
   */
  const trackVideoWatch = async (videoTitle: string, lessonId?: string) => {
    try {
      const chapterId = getCurrentChapterId()
      await progressService.recordVideoWatch(
        chapterId,
        lessonId || `video-${Date.now()}`,
        videoTitle
      )
      console.log(`记录视频观看: ${videoTitle}`)
    } catch (error) {
      console.error('记录视频观看失败:', error)
    }
  }
  
  /**
   * 记录资料点击
   * @param materialName 资料名称
   * @param materialUrl 资料链接（可选）
   */
  const trackMaterialClick = async (materialName: string, materialUrl?: string) => {
    try {
      const chapterId = getCurrentChapterId()
      await progressService.recordMaterialClick(
        chapterId,
        materialName,
        materialUrl
      )
      console.log(`记录资料点击: ${materialName}`)
    } catch (error) {
      console.error('记录资料点击失败:', error)
    }
  }
  
  /**
   * 记录练习完成
   * @param exerciseName 练习名称
   * @param score 得分（可选）
   */
  const trackExerciseComplete = async (exerciseName: string, score?: number) => {
    try {
      const chapterId = getCurrentChapterId()
      await progressService.recordExerciseComplete(
        chapterId,
        exerciseName,
        score
      )
      console.log(`记录练习完成: ${exerciseName}${score ? `, 得分: ${score}` : ''}`)
    } catch (error) {
      console.error('记录练习完成失败:', error)
    }
  }
  
  /**
   * 开始页面访问追踪
   */
  const startPageTracking = () => {
    if (isTracking.value) return
    
    isTracking.value = true
    startTime.value = new Date()
    
    // 记录页面访问
    const chapterId = getCurrentChapterId()
    progressService.recordStudyAction({
      chapterId,
      actionType: 'material_click',
      details: `访问页面: ${route.path}`
    })
  }
  
  /**
   * 停止页面访问追踪
   */
  const stopPageTracking = () => {
    if (!isTracking.value || !startTime.value) return
    
    const endTime = new Date()
    const duration = Math.round((endTime.getTime() - startTime.value.getTime()) / 1000) // 秒
    
    // 如果停留时间超过30秒，记录为有效学习时间
    if (duration >= 30) {
      const chapterId = getCurrentChapterId()
      progressService.recordStudyAction({
        chapterId,
        actionType: 'material_click',
        details: `页面学习时长: ${duration}秒`
      })
    }
    
    isTracking.value = false
    startTime.value = null
  }
  
  /**
   * 自动追踪链接点击
   * 为页面中的链接添加点击追踪
   */
  const setupLinkTracking = () => {
    // 延迟执行，确保DOM已渲染
    setTimeout(() => {
      const links = document.querySelectorAll('a[href]')
      
      links.forEach(link => {
        const href = link.getAttribute('href')
        const text = link.textContent?.trim() || '未知链接'
        
        // 避免重复绑定事件
        if (link.hasAttribute('data-tracked')) return
        link.setAttribute('data-tracked', 'true')
        
        link.addEventListener('click', () => {
          // 只追踪外部链接和资料链接
          if (href && (href.startsWith('http') || href.includes('.pdf') || href.includes('.doc'))) {
            trackMaterialClick(text, href)
          }
        })
      })
    }, 1000)
  }
  
  /**
   * 自动追踪视频播放
   * 为页面中的视频添加播放追踪
   */
  const setupVideoTracking = () => {
    setTimeout(() => {
      const videos = document.querySelectorAll('video')
      
      videos.forEach((video, index) => {
        // 避免重复绑定事件
        if (video.hasAttribute('data-tracked')) return
        video.setAttribute('data-tracked', 'true')
        
        const videoTitle = video.getAttribute('title') || 
                          video.getAttribute('data-title') || 
                          `视频${index + 1}`
        
        let hasTracked = false
        
        const trackPlay = () => {
          if (!hasTracked) {
            trackVideoWatch(videoTitle, `video-${index + 1}`)
            hasTracked = true
          }
        }
        
        video.addEventListener('play', trackPlay)
        video.addEventListener('timeupdate', () => {
          // 当视频播放超过10秒时记录
          if (!hasTracked && video.currentTime > 10) {
            trackPlay()
          }
        })
      })
    }, 1000)
  }
  
  /**
   * 设置自动追踪
   */
  const setupAutoTracking = () => {
    setupLinkTracking()
    setupVideoTracking()
  }
  
  // 页面可见性变化处理
  const handleVisibilityChange = () => {
    if (document.hidden) {
      stopPageTracking()
    } else {
      startPageTracking()
    }
  }
  
  // 页面卸载处理
  const handleBeforeUnload = () => {
    stopPageTracking()
  }
  
  // 组件挂载时开始追踪
  onMounted(() => {
    startPageTracking()
    setupAutoTracking()
    
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', handleVisibilityChange)
    window.addEventListener('beforeunload', handleBeforeUnload)
  })
  
  // 组件卸载时停止追踪
  onUnmounted(() => {
    stopPageTracking()
    
    // 移除事件监听
    document.removeEventListener('visibilitychange', handleVisibilityChange)
    window.removeEventListener('beforeunload', handleBeforeUnload)
  })
  
  return {
    // 状态
    isTracking,
    
    // 方法
    trackVideoWatch,
    trackMaterialClick,
    trackExerciseComplete,
    startPageTracking,
    stopPageTracking,
    setupAutoTracking,
    getCurrentChapterId
  }
}

/**
 * 创建学习追踪指令
 * 可以在模板中使用 v-track-click="'资料名称'" 来追踪点击
 */
export const createTrackingDirective = () => {
  return {
    mounted(el: HTMLElement, binding: any) {
      const materialName = binding.value || el.textContent?.trim() || '未知资料'
      
      el.addEventListener('click', () => {
        // 这里需要访问当前组件的追踪实例
        // 由于指令的限制，我们直接使用 progressService
        const route = window.location.pathname
        const chapterIdMap: { [key: string]: string } = {
          '/chapter1': '1',
          '/chapter2': '2',
          '/chapter3-examples': '3', 
          '/chapter4-examples': '4',
          '/examples': '5'
        }
        
        const chapterId = chapterIdMap[route] || '1'
        progressService.recordMaterialClick(chapterId, materialName)
      })
    }
  }
}